import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, DATE_FORMAT,
    ROWSELECTION_FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT} from '../constants';
import TextInput from 'Shared/components/TextInput';
import SelectAlert from '../common/SelectAlert';
import WrappedSelect from '../common/WrappedSelect';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from './DealerSelectPanel';
import DateRangePicker from 'Shared/components/DateRangePicker';
import {conventSorter} from './utils';
import styles from './style.css';
import {deliveryOrderPostQuery, getDealersQuickly} from './api';
import {formatAmount, conventEnumValueToString, formatDateTime} from '../utils';
import {transportType} from '../Enum';
import moment from 'moment';
const FormItem = Form.Item;
class DeliveryOrderSelectPanel extends PureComponent {
    state = {
        keys: [],
        rows: [],
        dealerId: '',
        brandId: '',
        partSaleOrderCode: '',
        partOrderTypeId: '',
        code: '',
        submitDate: undefined,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        isFetching: false,
        data: {},
        message: '',
        currentCondition: {},
        showDealerSelectPanel: false
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
    onSelectDealer = data => {
        this.setState({
            dealerId: data.id,
            dealerCode: data.code,
            dealerName: data.name,
            showDealerSelectPanel: false
        });
    }
    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }
    onCloseDealerSelectPanel = () => {
        this.setState({showDealerSelectPanel: false});
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        deliveryOrderPostQuery(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const conventDate = (condition = {}) => {
            const {submitDate, ...others} = condition;
            if(!submitDate || submitDate.length === 0) return condition;
            return {
                ...others,
                beginSubmitDate: moment(submitDate[0]).toISOString(),
                endSubmitDate: moment(submitDate[1]).toISOString(),
            };
        };
        const condition = {
            brandId: this.state.brandId,
            dealerId: this.state.dealerId,
            partSaleOrderCode: this.state.partSaleOrderCode,
            partOrderTypeId: this.state.partOrderTypeId,
            code: this.state.code,
            submitDate: this.state.submitDate,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(conventDate(condition));
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onClickReset = () => {
        this.setState({
            dealerId: '',
            dealerCode: '',
            dealerName: '',
            brandId: '',
            partSaleOrderCode: '',
            partOrderTypeId: '',
            code: '',
            submitDate: undefined
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: [],
            rows: []
        });
    }
    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onSubmit = () => {
        if(!this.state.rows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'deliveryOrderSelectPanel.validate.part',
                defaultMessage: '请选择交货单'
            }));
        this.props.onSelect(this.state.rows[0], this.props.selectKey);
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const dealerInfo = this.state.dealerId ? {
            id: this.state.dealerId,
            code: this.state.dealerCode,
            name: this.state.dealerName
        } : null;
        const columns = [
            {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.sapTransferOrderCode',
                    defaultMessage: '调拨单号'
                }),
                sorter: true,
                dataIndex: 'sapTransferOrderCode'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.sapDeliveryCode',
                    defaultMessage: '交货单号'
                }),
                dataIndex: 'sapDeliveryCode'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.partSaleOrderCode',
                    defaultMessage: '订单编号'
                }),
                dataIndex: 'partSaleOrderCode'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.itemCount',
                    defaultMessage: '品种数'
                }),
                dataIndex: 'itemCount'
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.totalAmount',
                    defaultMessage: '总金额'
                }),
                dataIndex: 'totalAmount',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                render: text => conventEnumValueToString(transportType, text)
            }, {
                title: formatMessage({
                    id: 'deliveryOrderSelectPanel.column.submitDate',
                    defaultMessage: '提报日期'
                }),
                dataIndex: 'submitDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record, this.props.selectKey);
            }
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys
        };
        const selectRows = this.state.rows.length ? [{
            text: this.state.rows[0].code,
            value: this.state.rows[0].id
        }] : [];
        return (
            <Modal
                title={formatMessage({
                    id: 'deliveryOrderSelectPanel.show.query',
                    defaultMessage: '备件交货单查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'deliveryOrderSelectPanel.form.dealer',
                                defaultMessage: '总代'
                            })}
                            {...FORM_OPTIONS.item} >
                            <SearchSelect
                                allowClear
                                value={dealerInfo}
                                placeholder={this.props.intl.formatMessage({
                                    id: 'deliveryOrderSelectPanel.form.pleaseQuery',
                                    defaultMessage: '请输入查询'
                                })}
                                onSelect={this.onSelectDealer}
                                onSearch={this.onSearchDealer}
                                keyIndex="id"
                                labelMap={this.dealerLabelMap}
                                onClickSearchBtn={this.onClickSearchDealerBtn} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'deliveryOrderSelectPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="brandId"
                                value={this.state.brandId}
                                options={this.props.initEnum.brands}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'deliveryOrderSelectPanel.form.partSaleOrderCode',
                                defaultMessage: '订单编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="partSaleOrderCode"
                                value={this.state.partSaleOrderCode}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'deliveryOrderSelectPanel.form.partOrderTypeId',
                                defaultMessage: '订单类型'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="partOrderTypeId"
                                value={this.state.partOrderTypeId}
                                options={this.props.initEnum.partSaleOrderTypes}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'deliveryOrderSelectPanel.form.code',
                                defaultMessage: '交货单号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'deliveryOrderSelectPanel.form.submitDate',
                                defaultMessage: '提报日期'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DateRangePicker name="submitDate" value={this.state.submitDate}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'deliveryOrderSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'deliveryOrderSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    onRow={onRow}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }} />
                {
                    this.state.showDealerSelectPanel &&
                    <DealerSelectPanel
                        selectKey={data.dealerId}
                        onCancel={this.onCloseDealerSelectPanel}
                        onSelect={this.onSelectDealer} />
                }
            </Modal >
        );
    }
}

DeliveryOrderSelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    intl: PropTypes.object,
    onCancel: PropTypes.func,
};
import {injectIntl} from './intl';
import {connect} from 'react-redux';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const partSaleOrderTypes = initData.partSaleOrderTypes ? initData.partSaleOrderTypes.map(item => ({
            text: `${item.typeName}`,
            value: item.id
        })) : [];
        return {
            brands,
            partSaleOrderTypes
        };
    }
);

const mapStateToProps = state => ({
    initEnum: getInitData(state)
});
export default connect(mapStateToProps, null)(injectIntl(DeliveryOrderSelectPanel));
